package com.school.graduation.detailed.model;

import android.content.Context;
import android.os.Handler;
import android.os.Looper;

import com.google.gson.Gson;
import com.school.graduation.detailed.presenter.DetailedPresenterNew;
import com.school.graduation.model.Detailed;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class DetailedModelNew {
    private DetailedPresenterNew presenter;
    private Context context;
    public DetailedModelNew(Context context,DetailedPresenterNew presenter){
        this.context = context;
        this.presenter = presenter;
    }

    public void getDetailed(final String id){
        new Thread(new Runnable() {
            @Override
            public void run() {
                OkHttpClient client = new OkHttpClient();
                Request request = new Request.Builder()
                        .url("http://123.206.20.29:3000/goods/"+id)
                        .build();
                Call call = client.newCall(request);
                call.enqueue(new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {

                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        String str = response.body().string();
                        Gson gson = new Gson();
                        final Detailed detailed = gson.fromJson(str,Detailed.class);
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                presenter.initContent(detailed);
                            }
                        });
                    }
                });
            }
        }).start();
    }

    private void runOnUiThread(Runnable runnable){
        new Handler(Looper.getMainLooper()).post(runnable);
    }
}
